package com.example.ai.inventory.service;

import com.example.ai.inventory.entity.SalesOrder;
import com.example.ai.inventory.entity.SalesItem;
import com.example.ai.inventory.repository.SalesOrderRepository;
import com.example.ai.inventory.repository.SalesItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * 销售服务实现类
 */
@Service
public class SalesServiceImpl implements SalesService {
    
    @Autowired
    private SalesOrderRepository salesOrderRepository;
    
    @Autowired
    private SalesItemRepository salesItemRepository;
    
    @Autowired
    private ProductService productService;
    
    private final Random random = new Random();
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    
    @Override
    @Transactional
    public SalesOrder createSalesOrder(SalesOrder order) {
        // 生成销售单号
        String orderNo = generateOrderNo();
        order.setOrderNo(orderNo);
        
        // 检查库存是否充足
        checkInventory(order);
        
        // 计算销售总金额
        calculateTotalAmount(order);
        
        // 保存销售单
        SalesOrder savedOrder = salesOrderRepository.save(order);
        
        // 保存销售明细并更新商品库存
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            for (SalesItem item : order.getItems()) {
                item.setOrderId(savedOrder.getId());
                salesItemRepository.save(item);
                
                // 更新商品库存（销售出库）
                productService.updateProductStock(item.getProductId(), -item.getQuantity());
            }
        }
        
        return savedOrder;
    }
    
    @Override
    public SalesOrder getSalesOrderById(Long id) {
        SalesOrder order = salesOrderRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("销售单不存在：" + id));
        
        // 加载销售明细
        loadSalesItems(order);
        
        return order;
    }
    
    @Override
    public SalesOrder getSalesOrderByOrderNo(String orderNo) {
        SalesOrder order = salesOrderRepository.findByOrderNo(orderNo)
                .orElseThrow(() -> new RuntimeException("销售单不存在：" + orderNo));
        
        // 加载销售明细
        loadSalesItems(order);
        
        return order;
    }
    
    @Override
    public List<SalesOrder> getSalesOrders(LocalDateTime startTime, LocalDateTime endTime) {
        List<SalesOrder> orders;
        if (startTime != null && endTime != null) {
            orders = salesOrderRepository.findByCreateTimeBetween(startTime, endTime);
        } else {
            orders = salesOrderRepository.findAll();
        }
        
        // 加载每个订单的明细
        for (SalesOrder order : orders) {
            loadSalesItems(order);
        }
        
        return orders;
    }
    
    @Override
    public List<SalesItem> getSalesItemsByOrderId(Long orderId) {
        return salesItemRepository.findByOrderId(orderId);
    }
    
    @Override
    public List<SalesItem> getSalesHistoryByProductId(Long productId) {
        return salesItemRepository.findByProductId(productId);
    }
    
    /**
     * 生成销售单号
     */
    private String generateOrderNo() {
        String dateStr = LocalDateTime.now().format(formatter);
        int randomNum = 10000 + random.nextInt(90000); // 生成5位随机数
        return "SO" + dateStr + randomNum;
    }
    
    /**
     * 检查库存是否充足
     */
    private void checkInventory(SalesOrder order) {
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            for (SalesItem item : order.getItems()) {
                // 验证商品是否存在
                productService.getProductById(item.getProductId());
                
                // 检查库存是否充足
                int currentStock = productService.getProductById(item.getProductId()).getStock();
                if (currentStock < item.getQuantity()) {
                    throw new RuntimeException("商品库存不足：" + item.getProductId());
                }
            }
        }
    }
    
    /**
     * 计算销售总金额
     */
    private void calculateTotalAmount(SalesOrder order) {
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            double totalAmount = order.getItems().stream()
                    .mapToDouble(item -> item.getQuantity() * item.getUnitPrice())
                    .sum();
            order.setTotalAmount(totalAmount);
        }
    }
    
    /**
     * 加载销售明细
     */
    private void loadSalesItems(SalesOrder order) {
        List<SalesItem> items = salesItemRepository.findByOrderId(order.getId());
        order.setItems(items);
    }
}